﻿using Learun.Util;
using Learun.Util.SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;

namespace Learun.Application.IM
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创建人：研发部
    /// 日 期：2017.04.17
    /// 描 述：即时通讯消息内容
    /// </summary>
    public class IMMsgService
    {
        #region 仓储
        Repository<IMMsgEntity> _IMMsgRepository => new Repository<IMMsgEntity>();
        Repository<IMContactsEntity> _IMContactsRepository => new Repository<IMContactsEntity>();
        #endregion
        #region 构造函数和属性

        private string fieldSql;
        public IMMsgService()
        {
            fieldSql = @"
                t.F_MsgId,
                t.F_IsSystem,
                t.F_SendUserId,
                t.F_RecvUserId,
                t.F_Content,
                t.F_CreateDate,
                t.ProjectId,
                t.TypeId,
                F_IsRead
            ";
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取列表数据(最近的10条聊天记录)
        /// <summary>
        /// <returns></returns>
        public IEnumerable<IMMsgEntity> GetList(string sendUserId, string recvUserId)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(fieldSql);
                strSql.Append(" FROM LR_IM_Msg t where  (t.F_SendUserId = @sendUserId and  t.F_RecvUserId = @recvUserId ) or  (t.F_SendUserId = @recvUserId and  t.F_RecvUserId = @sendUserId ) ");

                Pagination pagination = new Pagination();
                pagination.page = 1;
                pagination.rows = 10;
                pagination.sidx = "F_CreateDate";
                pagination.sord = "DESC";

                //this.BaseRepository().ExecuteBySql(" Update LR_IM_Contacts Set F_ISREAD = 2 where  F_MyUserId = @sendUserId AND  F_OtherUserId =  @recvUserId  ",new { sendUserId , recvUserId });
                SqlSugarHelper.Db.Ado.ExecuteCommand(" Update LR_IM_Contacts Set F_ISREAD = 2 where  F_MyUserId = @sendUserId AND  F_OtherUserId =  @recvUserId  ", new { sendUserId, recvUserId });
                //return this.BaseRepository().FindList<IMMsgEntity>(strSql.ToString(),new { sendUserId, recvUserId }, pagination);
                return SqlSugarHelper.Db.SqlQueryable<IMMsgEntity>(strSql.ToString()).AddParameters(new { sendUserId, recvUserId }).ToPageList(pagination.page, pagination.rows);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取列表数据(小于某个时间点的5条记录)
        /// </summary>
        /// <param name="myUserId">我的ID</param>
        /// <param name="otherUserId">对方的ID</param>
        /// <param name="time">时间</param>
        /// <returns></returns>
        public IEnumerable<IMMsgEntity> GetListByTime(string myUserId, string otherUserId, DateTime time)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(fieldSql);
                strSql.Append(" FROM LR_IM_Msg t where  ((t.F_SendUserId = @myUserId and  t.F_RecvUserId = @otherUserId ) or  (t.F_SendUserId = @otherUserId and  t.F_RecvUserId = @myUserId )) AND t.F_CreateDate <= @time ");

                Pagination pagination = new Pagination();
                pagination.page = 1;
                pagination.rows = 5;
                pagination.sidx = "F_CreateDate";
                pagination.sord = "DESC";

                //return this.BaseRepository().FindList<IMMsgEntity>(strSql.ToString(), new { myUserId, otherUserId, time }, pagination);
                return SqlSugarHelper.Db.SqlQueryable<IMMsgEntity>(strSql.ToString()).AddParameters(new { myUserId, otherUserId, time }).ToPageList(pagination.page, pagination.rows);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取列表数据(大于某个时间的所有数据)
        /// </summary>
        /// <param name="myUserId">我的ID</param>
        /// <param name="otherUserId">对方的ID</param>
        /// <param name="time">时间</param>
        /// <returns></returns>
        public IEnumerable<IMMsgEntity> GetListByTime2(string myUserId, string otherUserId, DateTime time)
        {
            try
            {
                time = time.AddSeconds(1);
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(fieldSql);
                strSql.Append(" FROM LR_IM_Msg t where  ((t.F_SendUserId = @myUserId and  t.F_RecvUserId = @otherUserId ) or  (t.F_SendUserId = @otherUserId and  t.F_RecvUserId = @myUserId )) AND t.F_CreateDate >= @time Order By  F_CreateDate ASC ");

                //return this.BaseRepository().FindList<IMMsgEntity>(strSql.ToString(), new { myUserId, otherUserId, time });
                return SqlSugarHelper.Db.SqlQueryable<IMMsgEntity>(strSql.ToString()).AddParameters(new { myUserId, otherUserId, time }).ToList();

            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取列表分页数据
        /// <summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="sendUserId"></param>
        /// <param name="recvUserId"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public IEnumerable<IMMsgEntity> GetPageList(Pagination pagination, string sendUserId, string recvUserId, string keyword, string Isread,string ProjectId)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(@"
                    t.F_MsgId,
                    t.F_IsSystem,
                    t.F_SendUserId,
                    t.F_RecvUserId,
                    t.F_Content,
                    t.F_CreateDate,
                    t.Title,
                    p.ProjectName as ProjectId,
                    t.TypeId,
                    t.F_IsRead,
                    p.ProjectName
                ");
                
                strSql.Append(" FROM LR_IM_Msg t ");
                strSql.Append(" left join ec_project p ON p.ProjectId = t.ProjectId ");
                strSql.Append(" where t.F_RecvUserId = @sendUserId ");
                if (!string.IsNullOrEmpty(keyword)) {
                    keyword = "%" + keyword + "%";
                    strSql.Append(" AND t.Title like @keyword ");
                }
                if (!string.IsNullOrEmpty(Isread))
                {
                    strSql.Append(" AND t.F_IsRead = @Isread ");
                }
                //update by chenkai 20210421 单位平台时显示所有消息
                ProjectId = (string.IsNullOrEmpty(ProjectId) || ProjectId.ToLower() == "null") ? "" : ProjectId;
                if (!string.IsNullOrEmpty(ProjectId))
                {
                    strSql.Append(" AND t.ProjectId = @ProjectId");
                }
                //return this.BaseRepository().FindList<IMMsgEntity>(strSql.ToString(), new { sendUserId = sendUserId, recvUserId = recvUserId, keyword = keyword, Isread = Isread, ProjectId = ProjectId }, pagination);
                return SqlSugarHelper.Db.SqlQueryable<IMMsgEntity>(strSql.ToString()).AddParameters(new { sendUserId = sendUserId, recvUserId = recvUserId, keyword = keyword, Isread = Isread, ProjectId = ProjectId }).ToPageList(pagination.page, pagination.rows);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        public IEnumerable<IMMsgEntity> GetProjectMsg(string ProjectId, string userId)
        {
            string strSql = @"select 
                    t.F_MsgId,
	                t.F_IsSystem,
	                u.F_RealName as F_SendUserId,
	                t.F_RecvUserId,
	                t.F_Content,
                    t.F_CreateUserId,
	                t.F_CreateDate,
	                t.Title,
	                t.ProjectId,
	                t.TypeId,
	                t.F_IsRead,
                    p.ProjectName
                    from lr_im_msg t
                    left join lr_base_user u on u.F_UserId = t.F_SendUserId
                    left join ec_project p on t.ProjectId=p.ProjectId
                    where F_RecvUserId = @userId and F_IsRead = 0";

            //update by chenkai 20210421 单位平台时显示所有消息
            ProjectId = (string.IsNullOrEmpty(ProjectId) || ProjectId.ToLower() == "null") ? "" : ProjectId;
            if (!string.IsNullOrEmpty(ProjectId))
            {
                strSql += " and ProjectId = @ProjectId";
            }
            //return this.BaseRepository().FindList<IMMsgEntity>(strSql.ToString(), new { userId = userId, ProjectId = ProjectId });
            return SqlSugarHelper.Db.SqlQueryable<IMMsgEntity>(strSql.ToString()).AddParameters(new { userId = userId, ProjectId = ProjectId }).ToList();
        }

        public object GetMsgNotReadNum(string userId,string ProjectId)
        {
            string strSql = "select count(*) from lr_im_msg where F_RecvUserId = @userId and F_IsRead = 0";
            //update by chenkai 20210421 单位平台时显示所有消息
            ProjectId = (string.IsNullOrEmpty(ProjectId) || ProjectId.ToLower() == "null") ? "" : ProjectId;
            if (!string.IsNullOrEmpty(ProjectId))
            {
                strSql += " and ProjectId = @ProjectId";
            }
            return SqlSugarHelper.Db.Ado.SqlQuerySingle<IMMsgEntity>(strSql, new { userId = userId, ProjectId = ProjectId });
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue)
        {
            try
            {
                _IMMsgRepository.Delete(t=>t.F_MsgId == keyValue);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增）
        /// <param name="entity">实体数据</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(IMMsgEntity entity)
        {

            IMContactsEntity myContacts = new IMContactsEntity();
            IMContactsEntity otherContacts = new IMContactsEntity();

            myContacts.F_MyUserId = entity.F_SendUserId;
            myContacts.F_OtherUserId = entity.F_RecvUserId;
            myContacts.F_Content = entity.F_Content;

            otherContacts.F_MyUserId = entity.F_RecvUserId;
            otherContacts.F_OtherUserId = entity.F_SendUserId;
            otherContacts.F_Content = entity.F_Content;

            IMContactsEntity myContactsTmp = _IMContactsRepository.GetFirst(t => t.F_MyUserId.Equals(myContacts.F_MyUserId) && t.F_OtherUserId.Equals(myContacts.F_OtherUserId));
            IMContactsEntity otherContactsTmp = _IMContactsRepository.GetFirst(t => t.F_MyUserId.Equals(otherContacts.F_MyUserId) && t.F_OtherUserId.Equals(otherContacts.F_OtherUserId));
            SqlSugarHelper.Db.BeginTran();
            try
            {
                myContacts.F_IsRead = 2;
                if (myContactsTmp == null)
                {
                    myContacts.Create();
                    _IMContactsRepository.Insert(myContacts);
                }
                else
                {
                    myContacts.Modify(myContactsTmp.F_Id);
                    _IMContactsRepository.Update(myContacts);
                }

                otherContacts.F_IsRead = 1;
                if (otherContactsTmp == null)
                {
                    otherContacts.Create();
                    _IMContactsRepository.Insert(otherContacts);
                }
                else
                {
                    otherContacts.Modify(otherContactsTmp.F_Id);
                    _IMContactsRepository.Update(otherContacts);
                }

                entity.Create();
                _IMMsgRepository.Insert(entity);

                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        public int UpdateIsread(string msgId, string isRead) {
            return SqlSugarHelper.Db.Ado.ExecuteCommand(" update lr_im_msg set F_IsRead = 1 where F_MsgId = '"+ msgId + "'" );
        }
        #endregion
    }
}
